import json, os

from flask import Flask, request, jsonify

# 实例化对象

app = Flask(__name__)
# 加载配置文件
from config import Config

app.config.from_object(Config)
# 跨域配置
from flask_cors import CORS

CORS(app)
# 实现orm,对象关系映射
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)


# 创建分类表
class Cate(db.Model):
    __tablename__ = 'cate'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), unique=True)
    level = db.Column(db.Integer, default=1)  # 等级
    pid = db.Column(db.Integer, default=0)  # 父id


class Course(db.Model):
    __tablename__ = 'course'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), unique=True)  # 名称唯一
    description = db.Column(db.Text, default='')  # 描述
    tname = db.Column(db.String(50), default='')  # 讲师
    pic = db.Column(db.String(255), default='')  # 图片
    vedios = db.Column(db.String(255), default='')  # 视频['','']
    status = db.Column(db.Integer, default=1)  # 审核状态
    reason = db.Column(db.String(255), default='')  # 失败原因
    cid = db.Column(db.Integer, db.ForeignKey('cate.id'))  # 所属分类


# db.create_all()


# 图片上传
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    file.save(os.path.join('./static/', file.filename))
    return jsonify({"code": 200, 'pic': file.filename})


# 课程管理
@app.route('/courseM', methods=['POST', 'GET'])
def courseM():
    if request.method == 'POST':
        # 接收客户传递的参数
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造数据

        course = Course(name=data['name'], description=data['description'], tname=data['tname'], pic=data['pic'],
                        vedios=json.dumps(data['vedios'], ensure_ascii=False), cid=data['cid'])

        # 添加
        db.session.add(course)
        # 提交
        db.session.commit()
        # 返回
        return jsonify({'code': 200})
    elif request.method == "GET":
        id = request.args.get('id')
        if id:
            course = Course.query.filter_by(id=id).first()
            cour = {'id': course.id, 'name': course.name, 'description': course.description, 'tname': course.tname,
                    'pic': course.pic, 'vedios': course.vedios, 'cid': course.cid}
            return jsonify({"code": 200, 'course': cour})

        # 获取参数
        # 当前点击的页面，如果没点击默认为1
        page = int(request.args.get('page'))
        # 每页显示多少条
        size = int(request.args.get('size'))
        # 读取数据
        start = (page - 1) * size
        course = Course.query.offset(start).limit(size)

        # 对结果解析
        list = []
        if course:
            for i in course:
                list.append({'id': i.id, 'name': i.name, 'pic': i.pic, 'tname': i.tname})
        # 获取共有多少条记录
        total = Course.query.count()
        # 返回
        return jsonify({"code": 200, 'list': list, 'total': total})
        # 获取id


if __name__ == "__main__":
    app.run()